var express = require('express');
var router = express.Router();

var core = require('core');
var config = core.config;
var error = core.error;
var request = require('request');
/* GET home page. */

var GET = {
    index : function(req, res, next){
        console.log(req.cookies);
        res.render('login', { title: 'Express' });
    },
    out   : function(req, res, next){
        // res.clearCookie(config.sid, { path: '/', expires: -1, maxAge: 0 });
        res.deleteSession("user");
        res.redirect('/index');
    }
};

var POST = function(req, res, next){

    var data = {
        name : req.body.username,
        pwd  : req.body.password
    };

    var authKey = core.sort(data);
    data.authKey = authKey;
    request({
        url: core.config.api +'api/merchant/login',
        method: "POST",
        json: true,
        headers: {
            "content-type": "application/json"
        },
        body: data
    }, function(err, response, body) {
        if (!err && response.statusCode == 200){
            if(!body.code)
                res.session('user', body.data);

            res.send(body);
        }else res.send(error(500))

    });

};

router.get('/', GET.index);
router.get('/out', GET.out);
router.post('/', POST);

module.exports = router;
